package com.web.qualification.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.sun.deploy.net.URLEncoder;
import com.web.common.BaseResult;
import com.web.common.enums.BaseStatus;
import com.web.common.enums.PendingAction;
import com.web.config.ExcelStylerUtil;
import com.web.customer.entity.Customer;
import com.web.customer.service.CustomerService;
import com.web.pendingList.service.PendingListService;
import com.web.qualification.entity.CustomerQualification;
import com.web.qualification.service.CustomerQualificationService;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wenzhuo
 * @create 2024-05-08 2024/5/8
 */
@RestController
@CrossOrigin
@RequestMapping("/qualification")
public class CustomerQualificationController {

    @Autowired
    private CustomerQualificationService qualificationService;

    @Autowired
    private PendingListService pendingListService;

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value = "/qualificationList")
    public BaseResult<List<CustomerQualification>> getCustomerQualificationList(@ModelAttribute CustomerQualification qualification){

        List<CustomerQualification> qualificationList = qualificationService.getAllCustomerQualification(qualification);

        return new BaseResult(BaseStatus.SUCCESS.getCode(),qualificationList);
    }

    @RequestMapping(value = "/downTemplate")
    public void exportPosition(HttpServletResponse response) throws IOException {

        String fileName = "客户资质模板";
        String sheetName = "客户资质数据";
        ExportParams exportParams = new ExportParams(fileName,sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStylerUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, CustomerQualification.class, new ArrayList<CustomerQualification>());

        //将表格输出
        fileName = URLEncoder.encode(fileName,"UTF8");
        //设置返回数据类型
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("/upload")
    public BaseResult<String> importQualificationList(@RequestParam(name = "qualificationFile") MultipartFile file,String userName) throws Exception {
        /*使用easypoi获取文件数据*/
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        /*获取excel表格中数据，并封装为一个结果对象*/
        List<CustomerQualification> qualifications = ExcelImportUtil.importExcel(file.getInputStream(), CustomerQualification.class, params);

        if(qualifications.isEmpty()){
            return new BaseResult(BaseStatus.QUALIFICATION_DATA_NOT_IMPORT.getCode(),BaseStatus.QUALIFICATION_DATA_NOT_IMPORT.getDesc());
        }

        //TODO:检验输入数据是否正确

        //校验上传的客户资质数据和客户基本信息是否已存在.
        for (CustomerQualification qualification : qualifications) {
            List<Customer> customer = customerService.getCustomerList(qualification.getCustomerNo(), null, null);
            if(customer.isEmpty()){
                return new BaseResult(BaseStatus.CUSTOMER_NOT_EXIST.getCode(),BaseStatus.CUSTOMER_NOT_EXIST.getDesc());
            }

            if(qualificationService.getCustomerQualificationByCusNo(qualification.getCustomerNo()) != null){
                return new BaseResult(BaseStatus.QUALIFICATION_DATA_EXIST.getCode(),BaseStatus.QUALIFICATION_DATA_EXIST.getDesc());
            }

        }

        //新增qualification相关的审批记录
       return pendingListService.addQualificationPending(PendingAction.ADD.getAction(),CustomerQualification.MODULE,userName,qualifications);

    }

    @PostMapping(value = "/deleteQualification")
    public BaseResult deleteQualification(@RequestParam("customerNo") Integer customerNo,String userName){
        //根据客户号判断客户资质是否存在
        CustomerQualification qualification = qualificationService.getCustomerQualificationByCusNo(customerNo);
        if(qualification == null){
            return new BaseResult<>(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        //生成一笔Pending记录
        return pendingListService.deleteQualificationPending(PendingAction.DEL.getAction(), CustomerQualification.MODULE, userName, qualification);
    };



    @PostMapping(value = "/modifyQualification")
    public BaseResult modifyQualification(@ModelAttribute CustomerQualification qualificationNew,String userName){
        //根据客户号判断客户资质是否存在
        CustomerQualification qualificationOld = qualificationService.getCustomerQualificationByCusNo(qualificationNew.getCustomerNo());
        if(qualificationOld == null){
            return new BaseResult<>(BaseStatus.QUALIFICATION__DATA_EXCEPTION.getCode(),BaseStatus.QUALIFICATION__DATA_EXCEPTION.getDesc());
        }

        //新增Customer审批记录,将修改的数据放入到临时表中.
        return pendingListService.handleModifyQualification(qualificationOld,qualificationNew,userName);
    };

    @PostMapping(value = "/downQualification")
    public BaseResult downQualification(@ModelAttribute CustomerQualification qualification,String userName,HttpServletResponse response) {

        //查询客户资质数据是否为空
        List<CustomerQualification> qualificationList = qualificationService.getAllCustomerQualification(qualification);

        if (qualificationList.isEmpty()){
            return  new BaseResult<>(BaseStatus.QUALIFICATION__DATA_NOT_EXIST.getCode(),BaseStatus.QUALIFICATION__DATA_NOT_EXIST.getDesc());
        }

        //生成PDF
        if(!qualificationService.downloadPdf(qualificationList,userName)){
            return new BaseResult<>(BaseStatus.EXPORT__DATA_EXCEPTION.getCode(),BaseStatus.EXPORT__DATA_EXCEPTION.getDesc());
        }
        return  new BaseResult<>(BaseStatus.SUCCESS.getCode(),BaseStatus.DOWN_PDF_SUCCESS.getDesc());
    }

}
